<template>
  <ElDialog v-model="dialogVisible" :show-close="false" :scroll="true" maxHeight="500" :width="700">
    <template #header>
      <h3 class="titleClass">表头设置</h3>
    </template>
    <el-scrollbar height="500px">
      <div class="tableView" v-loading="formLoading">
        <div v-for="(item, index) in tableTitleList" :key="index">
          <div class="tableViewItem" v-if="!item.label.includes('序号')">
            <div class="label">{{ item.label }}</div>
            <el-input-number
              :min="50"
              :max="800"
              v-model="item.width"
              controls-position="right"
              class="!w-160px"
            />
            <!-- maxlength="3":min="0"
              :precision="0" -->
            <div class="rightOpera">
              <el-button
                :type="index === tableTitleList.length - 1 ? '' : 'primary'"
                :disabled="index === tableTitleList.length - 1"
                @click="downward(index)"
                class="btn"
              >
                <Icon icon="ep:arrow-down-bold" />
              </el-button>
              <el-button
                :type="
                  !item.label.includes('序号')
                    ? index == 1
                      ? ''
                      : 'primary'
                    : index == 0
                    ? ''
                    : 'primary'
                "
                :disabled="!item.label.includes('序号') ? index == 1 : index == 0"
                @click="upward(index)"
                class="btn"
              >
                <Icon icon="ep:arrow-up-bold" />
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
    <template #footer>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="defaultData" :loading="formLoading">恢复默认</el-button>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import * as UserApi from '@/api/system/user'
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

// 处理输入负数和.开头
// const handleInput = (index) => {
//   const item = tableTitleList.value[index]
//   let inputValue = item.width
//   if (inputValue === '.') {
//     item.width = null
//   } else {
//     inputValue = inputValue.toString() // 将输入值转为字符串
//     if (inputValue.startsWith('.')) {
//       // 如果输入值以小数点开头，则修正输入值
//       inputValue = inputValue.substring(1) // 去掉开头的小数点
//       inputValue = parseFloat(`0${inputValue}`) // 添加一个 0，然后转为浮点数
//     } else {
//       inputValue = parseFloat(inputValue) // 将输入值转为浮点数
//     }
//     if (isNaN(inputValue) || inputValue < 0) {
//       item.width = null
//     } else {
//       item.width = inputValue
//     }
//   }
// }
/**param:
 * {
  type:'index',        //是否是序号  不是则无这个字段
    label: '第一个表头', //表头中文
    field: 'first',     //字段名称
    width: 100,         //宽度
    align:'center',     //对齐方式 ['left', 'center', 'right']
    headerAlign:'center',  //表头对齐方式 ['left', 'center', 'right']
    isTable: true,         //是否是表格
    isSearch:false,         //是否搜索   保留
    isForm:false,           //是否表单   保留
    formatter: dateFormatter,                //数据翻译方法，类比字典
    dictType: DICT_TYPE.SYSTEM_MAIL_SEND_STATUS, //字典名称
    dictClass: 'number',                        //字典值类型  ['number', 'boolean', '其他所有类型']
  }
*/

const tableTitleList = ref<any[]>([]) // 表头列表
/** 打开弹窗 */
const codeName = ref()
const open = async (tableType: string[], code: string) => {
  codeName.value = code
  let tableData = JSON.parse(JSON.stringify(tableType))
  tableData = tableData.filter((item) => item.label !== '操作')
  getTableTitle(tableData)
}
/** 提交 */
const submitForm = async () => {
  // 提交请求tableTitleList.value
  formLoading.value = true
  try {
    const widthData = {
      code: codeName.value,
      labels: tableTitleList.value
    }
    await UserApi.getUserConfigWidth(widthData)
    emit('refresh')
    message.success('修改成功')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

// 恢复默认值
const defaultData = async () => {
  formLoading.value = true
  try {
    const widthData = {
      code: codeName.value,
      labels: []
    }
    await UserApi.getUserConfigWidth(widthData)
    emit('refresh')
    message.success('恢复默认成功')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

/**获取表头数据 **/
const getTableTitle = async (tableType: string[]) => {
  tableTitleList.value = tableType
  dialogVisible.value = true
}
/**向上 */
const upward = async (index: number) => {
  let clickItem = JSON.parse(JSON.stringify(tableTitleList.value[index]))
  tableTitleList.value.splice(--index, 0, clickItem)
  index += 2
  tableTitleList.value.splice(index, 1)
}
/**向下 */
const downward = async (index: number) => {
  let clickItem = JSON.parse(JSON.stringify(tableTitleList.value[index]))
  index += 2
  tableTitleList.value.splice(index, 0, clickItem)
  index -= 2
  console.log(index)
  tableTitleList.value.splice(index, 1)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['refresh']) // 定义 success 事件，用于操作成功后的回调
</script>
<style lang="scss" scoped>
.tableViewItem {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
}
.label {
  width: 260px;
  font-size: 18px;
}
.rightOpera {
  width: 90px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.titleClass {
  font-size: 24px;
}
.btn {
  width: 30px;
  height: 30px;
  // background: #409eff;
  // color: #fff;
  // display: flex;
  // align-items: center;
  // justify-content: center;
}
</style>
